﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.DeviceLedger
{
    /// <summary>
    /// 设备台账列表窗体代码
    /// </summary>
    public partial class DeviceLedgerForm : DevExpress.XtraEditors.XtraForm
    {
        public DeviceLedgerForm()
        {
            InitializeComponent();
        }


        private int pageIndex = 1; // 当前页码
        private int pageSize = 3; // 每页显示的记录数
        private int totalCount = 0; // 总记录数
        private int totalPages = 0;// 总页数


        /// </summary>
        /// 初始化或刷新设备台账列表，并绑定到GridControl，支持条件查询和操作按钮。
        /// </summary>
        /// <param name="deviceLedgerSerialNum">设备台账序列号（可选，等值查询）</param>
        /// <param name="deviceLedgerCode">设备台账编码（可选，等值查询）</param>
        /// <param name="deviceLedgerName">设备台账名称（可选，模糊查询）</param>
        public async Task ReInit(string deviceLedgerSerialNum = "", string deviceLedgerCode = "", string deviceLedgerName = "")
        {
            // 用于存放查询到的设备台账数据
            List<DeviceLedgerOutput> deviceLedgerOutputs = new List<DeviceLedgerOutput>();

            // 如果任一查询条件为空，则加载全部数据
            if (string.IsNullOrEmpty(deviceLedgerSerialNum) || string.IsNullOrEmpty(deviceLedgerCode) || string.IsNullOrEmpty(deviceLedgerName))
            {
                // 调用无条件查询方法，获取所有设备台账数据（分页）
                deviceLedgerOutputs = await GetDeviceLedgerList();
            }
            // 根据条件查询设备台账数据（分页）
            deviceLedgerOutputs = await GetDeviceLedgerListByCondition(deviceLedgerSerialNum, deviceLedgerCode, deviceLedgerName);

            // 绑定数据到GridControl控件，显示在界面上
            gridControl1.DataSource = deviceLedgerOutputs;

            // 获取GridView对象，用于设置列和操作按钮
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                // 清空现有列，重新添加所有需要显示的列
                gridView.Columns.Clear();
                gridView.Columns.AddVisible("Id", "编号");
                gridView.Columns.AddVisible("DeviceLedgerSerialNum", "设备台账序列号");
                gridView.Columns.AddVisible("DeviceLedgerCode", "设备台账编码");
                gridView.Columns.AddVisible("DeviceLedgerName", "设备台账名称");
                gridView.Columns.AddVisible("DeviceTypeName", "设备类型名称");
                //gridView.Columns.AddVisible("DeviceStatues", "设备状态");
                gridView.Columns.AddVisible("DeviceStatusText", "设备状态");
                gridView.Columns.AddVisible("DeviceSpeciFication", "设备规格");
                gridView.Columns.AddVisible("DeviceType", "设备类型");
                gridView.Columns.AddVisible("DeviceNum", "设备数量");
                gridView.Columns.AddVisible("DeviceBeginTime", "设备开始时间");
                gridView.Columns.AddVisible("DeviceEnterTime", "设备入库时间");
                gridView.Columns.AddVisible("SupplierName", "供应商名称");
                gridView.Columns.AddVisible("WorkShopName", "车间名称");
                gridView.Columns.AddVisible("Devicelocation", "设备位置");
                gridView.Columns.AddVisible("DeviceuseDepartments", "设备使用部门");
                gridView.Columns.AddVisible("DeviceHead", "设备负责人");
                gridView.Columns.AddVisible("DeviceRemark", "设备备注");
                gridView.Columns.AddVisible("CreatedBy", "创建人");

                // 为日期时间列设置格式
                var createdTimeColumn = gridView.Columns.AddVisible("CreatedTime", "创建时间");
                var updatedTimeColumn = gridView.Columns.AddVisible("UpdatedTime", "更新时间");
                // 设置日期时间格式为 yyyy-MM-dd HH:mm:ss
                createdTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                createdTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                updatedTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                updatedTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                // 如果还没有“操作”列，则添加操作列（包含删除和编辑按钮）
                if (gridView.Columns["操作"] == null)
                {
                    // 添加“操作”列
                    var col = gridView.Columns.AddVisible("操作", "操作");

                    // 设置为非绑定列（自定义按钮）
                    col.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    // 始终显示按钮
                    col.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                    // 创建按钮编辑器
                    RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                    buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor; // 隐藏文本框，仅显示按钮
                    buttonEdit.Buttons.Clear();
                    // 添加“删除”按钮
                    buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                    {
                        Caption = "删除",
                        Kind = ButtonPredefines.Glyph,
                        // 可选：设置按钮图片为 null，仅显示文字
                        ImageOptions = { Image = null } // 不显示图片
                    });
                    // 添加“编辑”按钮
                    buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                    {
                        Caption = "编辑",
                        Kind = ButtonPredefines.Glyph,
                        // 可选：设置按钮图片为 null，仅显示文字
                        ImageOptions = { Image = null } // 不显示图片
                    });
                    // 按钮点击事件处理
                    buttonEdit.ButtonClick += async (s, a) =>
                    {
                        // 获取当前选中的行
                        var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                        var rowHandle = view.FocusedRowHandle;
                        var row = view.GetRow(rowHandle) as DeviceLedgerOutput;
                        if (row != null)
                        {
                            if (a.Button.Index == 0)// 删除按钮
                            {
                                long id = row.Id;
                                // 调用删除方法
                                DeletedDeviceLedger(id);
                            }
                            else if (a.Button.Index == 1)// 编辑按钮
                            {
                                // 弹出编辑窗口，回显数据并支持修改
                                using (var client = new HttpClient())
                                {
                                    // 获取当前设备台账详细信息
                                    var response = client.GetStringAsync($"http://localhost:5229/api/DeviceLedger/GetDeviceLedgerValue?id={row.Id}").Result;
                                    var deviceLedger = JsonConvert.DeserializeObject<ApiResult<DeviceLedgerOutput>>(response);
                                    deviceLedger.Data.Id = row.Id;
                                    DeviceLedgerEditForm deviceLedgerEditForm = new DeviceLedgerEditForm();
                                    // 加载下拉选项
                                    await deviceLedgerEditForm.GetSeelct();
                                    // 回显数据
                                    deviceLedgerEditForm.GetDeviceLedgerData(deviceLedger.Data);
                                    // 显示编辑窗口
                                    var result = deviceLedgerEditForm.ShowDialog();
                                    if (result == DialogResult.OK)
                                    {
                                        // 编辑成功后，刷新设备台账列表
                                        await ReInit();
                                    }
                                }
                            }
                        }
                    };
                    // 将按钮编辑器赋给“操作”列
                    col.ColumnEdit = buttonEdit;
                }
            }
        }

        /// <summary>
        /// 根据条件获取设备台账列表（带分页）。
        /// </summary>
        /// <param name="deviceLedgerSerialNum">设备台账序列号（等值查询）</param>
        /// <param name="deviceLedgerCode">设备台账编码（等值查询）</param>
        /// <param name="deviceLedgerName">设备台账名称（模糊查询）</param>
        /// <returns>设备台账输出列表</returns>
        public async Task<List<DeviceLedgerOutput>> GetDeviceLedgerListByCondition(string deviceLedgerSerialNum, string deviceLedgerCode, string deviceLedgerName)
        {
            try
            {
                // 创建HttpClient实例，用于发送HTTP请求
                using (var client = new HttpClient())
                {
                    // 构造查询参数字符串，包含分页参数
                    string queryParams = $"PageIndex={pageIndex}&PageSize={pageSize}";

                    // 如果传入了设备台账序列号，则添加到查询参数（等值查询）
                    if (!string.IsNullOrEmpty(deviceLedgerSerialNum))
                    {
                        queryParams += $"&DeviceLedgerSerialNum={deviceLedgerSerialNum}";
                    }
                    // 如果传入了设备台账编码，则添加到查询参数（等值查询）
                    if (!string.IsNullOrEmpty(deviceLedgerCode))
                    {
                        queryParams += $"&DeviceLedgerCode={deviceLedgerCode}";
                    }
                    // 如果传入了设备台账名称，则添加到查询参数（模糊查询）
                    if (!string.IsNullOrEmpty(deviceLedgerName))
                    {
                        queryParams += $"&DeviceLedgerName={deviceLedgerName}";
                    }

                    // 发送GET请求到API，获取设备台账列表数据
                    var response = await client.GetStringAsync($"http://localhost:5229/api/DeviceLedger/GetDeviceLedgerList?{queryParams}");

                    // 反序列化API返回的JSON数据为ApiPaging<DeviceLedgerOutput>对象，并返回分页数据
                    return JsonConvert.DeserializeObject<ApiPaging<DeviceLedgerOutput>>(response).PageData;
                }
            }
            catch (Exception ex)
            {
                // 查询过程中发生异常，弹窗提示错误信息，并返回空列表
                MessageBox.Show($"查询出错：{ex.Message}");
                return new List<DeviceLedgerOutput>();
            }
        }
        /// <summary>
        /// 加载设备台账列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeviceLedgerForm_Load(object sender, EventArgs e)
        {
            await ReInit();
        }
        /// <summary>
        /// 删除设备台账
        /// </summary>
        /// <param name="id"></param>
        private async void DeletedDeviceLedger(long id)
        {
            using (var client = new HttpClient())
            {
                var response =await client.DeleteAsync($"http://localhost:5229/api/DeviceLedger/DeleteDeviceLedger?id={id}");
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功");
                    // 重新加载设备台账列表
                    DeviceLedgerForm_Load(null, null);
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
        }

        /// <summary>
        /// 获取设备台账列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private async Task<List<DeviceLedgerOutput>> GetDeviceLedgerList()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync($"http://localhost:5229/api/DeviceLedger/GetDeviceLedgerList?PageIndex={pageIndex}&PageSize={pageSize}");
                var result = JsonConvert.DeserializeObject<ApiPaging<DeviceLedgerOutput>>(response);
                // 获取总记录数
                totalCount = result.TotalCount;

                // 计算总页数（向上取整）
                totalPages = (int)Math.Ceiling((totalCount * 1.0) / pageSize);
                return result.PageData;
            }
        }

        /// <summary>
        /// 新增设备台账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddDeviceLedgerButton1_Click(object sender, EventArgs e)
        {
            DeviceLedgerAddForm deviceLedgerAddForm = new DeviceLedgerAddForm();
            deviceLedgerAddForm.ShowDialog();
            if (deviceLedgerAddForm.DialogResult == DialogResult.OK)
            {
                // 重新加载设备台账列表
                DeviceLedgerForm_Load(sender, e);
            }
        }


        /// <summary>
        /// 查询设备台账按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SelectQueryButton2_Click(object sender, EventArgs e)
        {
            // 获取界面上输入的查询条件：设备台账序列号、设备台账编码、设备台账名称
            string deviceLedgerSerialNum = DeviceLedgerSerialNum.Text.Trim();
            string deviceLedgerCode = DeviceLedgerCode.Text.Trim();
            string deviceLedgerName = DeviceLedgerName.Text.Trim();

            // 调用ReInit方法，按条件异步查询设备台账数据并刷新表格
            await ReInit(deviceLedgerSerialNum, deviceLedgerCode, deviceLedgerName);

            // 获取GridView对象，用于显示查询结果
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                // 弹窗提示查询到的记录条数
                MessageBox.Show($"查询到 {gridView.RowCount} 条记录");
            }
        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ResetButton5_Click(object sender, EventArgs e)
        {
            DeviceLedgerSerialNum.Text = "";
            DeviceLedgerCode.Text = "";
            DeviceLedgerName.Text = "";

            await ReInit();
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private async void PrevPageButton3_Click(object sender, EventArgs e)
        {
            // 判断当前是否为第一页
            if (pageIndex <= 1)
            {
                MessageBox.Show("已经是第一页了！");
                return;
            }
            // 页码减一，切换到上一页
            pageIndex -= 1;
            // 重新加载设备台账列表
            await ReInit();
        }

        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private async void NextPageButton4_Click(object sender, EventArgs e)
        {
            // 判断当前是否为最后一页
            if (pageIndex >= totalPages)
            {
                MessageBox.Show("已经是最后一页了！");
                return;
            }
            // 页码加一，切换到下一页
            pageIndex += 1;
            // 重新加载设备台账列表
            await ReInit();
        }
    }
}